package com.apes.scm.masterdata.product.service;

import com.apes.scm.masterdata.product.model.FaCategory;
import com.apes.scm.masterdata.product.repository.FaCategoryRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fa.service
 * @ClassName: FaCategoryService
 * @Author: PengZiFeng
 * @Description: 资产类别服务
 * @CreateTime: 2021-08-13 11:48
 * @Version: 1.0
 */
@Service("faCategoryService")
public class FaCategoryService extends DomainService {
    @Autowired
    FaCategoryRepository faCategoryRepository;

    /**
     * 保存
     */
    public FaCategory save(SimpleRequest request) {
        FaCategory faCategory = request.getO(FaCategory.class);
        faCategory.setLevels(Tools.isNull(faCategory.getParents()) ? 1 : faCategory.getParents().getLevels() + 1);
        if (faCategory.getId() != null) {
            if (faCategoryRepository.findOne(faCategory.getId()) != null) {
                throw new RuntimeException("资产类别【" + faCategory.getId() + "】在系统中已存在。");
            }
        }
        return faCategoryRepository.saveAndFlush(faCategory);
    }

    /**
     * 修改
     */
    public FaCategory update(SimpleRequest request) {
        FaCategory faCategory = request.getO(FaCategory.class);
        faCategory.setLevels(Tools.isNull(faCategory.getParents()) ? 1 : faCategory.getParents().getLevels() + 1);
        return faCategoryRepository.saveAndFlush(faCategory);
    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request) {
        FaCategory faCategory = request.getO(FaCategory.class);
        faCategoryRepository.delete(faCategory.getId());
        return "删除成功";
    }

    /**
     * 查询所有
     */
    public List<FaCategory> findAllForTree(SimpleRequest request) {
        List<FaCategory> faCategoryList = faCategoryRepository.findAll();
        return faCategoryList;
    }

}
